package tgc.edu.library.web.controller;

import java.util.HashSet;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import tgc.edu.library.custom.CommonController;
import tgc.edu.library.entity.BookType;
import tgc.edu.library.entity.Record;
import tgc.edu.library.web.form.RecordForm;


@Controller
@RequestMapping("/record")
public class RecordController extends CommonController<Record, Integer, RecordForm>{

	@Override
	public Specification<Record> buildSpec(RecordForm form) {
		Specification<Record> specification=new Specification<Record>() {

			private static final long serialVersionUID = 1L;

			@Override
			public Predicate toPredicate(Root<Record> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				HashSet<Predicate> rules=new HashSet<>();
				String search = form.getSearch();
				if(StringUtils.hasText(search)) {
					Predicate username = cb.like(root.get("username"), "%"+search+"%");
					Predicate operation = cb.like(root.get("operation"), "%"+search+"%");
					Predicate date = cb.like(root.get("date"), "%"+search+"%");
					Predicate time = cb.like(root.get("time"), "%"+search+"%");
					Predicate or = cb.or(username, operation,date,time);
					rules.add(or);
				}
				return cb.and(rules.toArray(new Predicate[rules.size()]));
			}
		};
		return specification;
	}
	
}
